﻿using System;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;

using Light.Utility;
using Light.Framework.Contract;
using System.ComponentModel;

namespace Light.Framework.Model
{

    /// <summary>
    /// 实体基类
    /// </summary>
    [Serializable]
    public abstract class Entity : IEntity
    {
        internal protected readonly Hashtable table = new Hashtable();

        #region IEntity 成员

        /// <summary>
        /// 唯一标识
        /// </summary>
        [PrimaryKey(Name = "ID", UnsavedValue = "00000000-0000-0000-0000-000000000000")]
        [DisplayName("唯一标识")]
        public virtual string ID { get; set; }

        /// <summary>
        /// 是否为新实例
        /// </summary>
        public bool IsNew
        {
            get
            {
                return ID == Guid.Empty.ToString() || String.IsNullOrWhiteSpace(ID);
            }
        }

        /// <summary>
        /// 校验数据合法性
        /// </summary>
        /// <returns></returns>
        [NonJsonSerialize]
        public bool IsValidated
        {
            get
            {
                errorMessages.Clear();
                ValidateRules();
                return errorMessages.Count == 0;
            }
        }

        /// <summary>
        /// 获取错误消息
        /// </summary>
        /// <returns></returns>
        public string GetErrorMessage()
        {
            errorMessages.Clear();
            ValidateRules();
            return String.Join(" ", errorMessages.ToArray());
        }

        /// <summary>
        /// 添加数据检验规则
        /// </summary>
        protected virtual void ValidateRules()
        {

        }


        List<string> errorMessages = new List<string>();
        protected void AddValidateRules(bool validated, string message)
        {
            if (!validated)
            {
                errorMessages.Add(message + "；");
            }

        }

        #endregion

        /// <summary>
        /// 仅传值
        /// </summary>
        public string Tag { get; set; }

        public void SetValue(string key, object value)
        {
            if (!table.ContainsKey(key))
                table.Add(key, value);
            else
                table[key] = value;
        }

        public T GetValue<T>(string key)
        {
            T value = default(T);

            object obj = table[key];
            if (obj != null)
                value = (T)obj;

            return value;
        }

        public T GetValue<T>(string key, T defaultValue)
        {
            T value = defaultValue;

            object obj = table[key];
            if (obj != null && !String.IsNullOrEmpty(obj.ToString()))
                value = (T)obj;
            if (typeof(T) == typeof(DateTime) && ((DateTime)obj) == default(DateTime))
                value = defaultValue;

            return value;
        }
    }
}
